﻿using Hd.AbpCoding.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;

namespace Hd.AbpCoding.Projects
{
    public class DomainDescEfCoreRepository : EfCoreRepository<AbpCodingDbContext, DomainDesc, Guid>, IDomainDescRepository
    {
        public DomainDescEfCoreRepository(IDbContextProvider<AbpCodingDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public async Task<DomainDesc> FindByNameAsync(Guid projectId, string name, CancellationToken cancellationToken = default)
        {
            return await this.Where(x => x.ProjectId == projectId)
                  .Where(x => x.Name == name)
                  .FirstOrDefaultAsync(GetCancellationToken(cancellationToken));
        }

        public async Task<int> GetCountAsync(Guid projectId, string filter = null, CancellationToken cancellationToken = default)
        {
            return await this.Where(x => x.ProjectId == projectId)
                .WhereIf(!filter.IsNullOrEmpty(), new DomainDescFilterSpecification(filter))
                .CountAsync(GetCancellationToken(cancellationToken));
        }

        public async Task<List<DomainDesc>> GetListAllAsync(Guid projectId, CancellationToken cancellationToken = default)
        {
            return await this.Where(x => x.ProjectId == projectId)
                .ToListAsync(GetCancellationToken(cancellationToken));
        }

        public async Task<List<DomainDesc>> GetListAsync(Guid projectId, string filter = null, int skipCount = 0, int maxResultCount = int.MaxValue, string sorting = null, bool includeDetails = false, CancellationToken cancellationToken = default)
        {
            return await this.Where(x => x.ProjectId == projectId)
                   .WhereIf(!filter.IsNullOrEmpty(), new DomainDescFilterSpecification(filter))
                   .OrderBy(sorting ?? nameof(DomainDesc.CreationTime))
                   .PageBy(skipCount, maxResultCount)
                   .ToListAsync(GetCancellationToken(cancellationToken));
        }
    }
}
